'use strict'

const gulp = require('gulp');
const babelify = require('babelify');
const browserify = require('browserify');
const notifier = require('node-notifier');
const watchify = require('watchify');
const source = require('vinyl-source-stream');
const Path = require('path')
const fs = require('fs');
require('colors');
var exclude = ['express-session','express-mysql-session',
'express','mongoose','connect-mongo',
'http','socket.io','fs','path','body-parser',
'cookie','cookie-parser','uid-safe','mysql']
function processServer(bundler){
	exclude.forEach((v)=>{
		bundler.exclude(v);
	})
	bundler.transform('babelify');
}
function bundleServer(bundler){
	var start = new Date();
	bundler.bundle().on("error",(error)=>{
			notifier.notify({
			  'title': '编译错误',
			  'message' : error.toString()
			});
			console.log(error.toString().yellow);
	})
	.on("end",()=>{
		var useTime = (Date.now() - start);
		notifier.notify({
					'title': '编译完成',
					'message' : '用时'+useTime + 'ms'
				});
		console.log('编译完成 用时'.green+useTime.toString().yellow+'ms'.green)
	})
	.pipe(source('server.js'))
	.pipe(gulp.dest('build'));
}
var entry = 'serverCode//main.js'
gulp.task('buildServer',()=>{
	var b = browserify(entry);
	processServer(b);
	bundleServer(b);

});
gulp.task('watchServer',()=>{
  var bundler = 	watchify(browserify(entry),watchify.args);
	processServer(bundler);
	bundler.on('update',rebundle);
	return rebundle();
	function rebundle(){
		bundleServer(bundler)
	}
})









const _ = require('lodash')
gulp.task('buildActions',()=>{
	function processActions(){
		//console.log('开始处理actions'.blue);
		var data = fs.readFileSync(Path.join(__dirname,'./code/client/actions.js'),'utf-8');
		var actions = data.match(/\w+/g);
		var r = _.join(_.map(actions,(v)=>{return 'export var '+v+'="'+v+'"'}),";");
	//	console.log(r);
		fs.writeFileSync(Path.join(__dirname,'./tmp/actions.js'),r,'utf-8')
			console.log('actions更新完成'.blue);
	}
	processActions();
})
gulp.task('watchActions',['buildActions'],()=>{
	gulp.watch('code/client/actions.js', ['buildActions']);
})
function processClient(bundle){
	const fileMap={
		'reducerApi':Path.join(__dirname,'./code/client/reducer/reducermain.js'),
		'router':Path.join(__dirname,'./code/client/react/router.js'),
		'actions':Path.join(__dirname,'./tmp/actions.js')
	}

	return bundle.transform("babelify",{presets: ["react"],resolveModuleSource:(source,filename)=>{
		if(fileMap[source]){
			return fileMap[source];
		}
		return source;
	}});
}
function bundleClient(bundler){
	var start = new Date();
	bundler.bundle().on("error",(error)=>{
			notifier.notify({
				'title': '编译错误',
				'message' : error.toString()
			});
			console.log(error.toString().yellow);
	})
	.on("end",()=>{
		var useTime = (Date.now() - start);
		notifier.notify({
					'title': '编译完成',
					'message' : '用时'+useTime + 'ms'
				});
		console.log('编译完成 用时'.green+useTime.toString().yellow+'ms'.green)
	})
	.pipe(source('client.js'))
	.pipe(gulp.dest('staticFiles'));
}

gulp.task('buildClient',()=>{
	var b = processClient(browserify('./clientCode/main.js'));
	bundleClient(b);
})

gulp.task('watchClient',()=>{
	var b = processClient(watchify(browserify('./clientCode/main.js'),watchify.args));
	b.on('update',()=>{
		rebundle();
	})
	rebundle();
	function rebundle(){
		bundleClient(b);
	}

})


const plumber = require('gulp-plumber')
const less = require('gulp-less')
const autoprefixer = require('gulp-autoprefixer');
const gutil = require('gulp-util');
const concat = require('gulp-concat');

gulp.task('buildThird',function(){
	var targets=['node_modules/jquery/dist/jquery.js',
               'node_modules/bootstrap/dist/js/bootstrap.js',
               'node_modules/jssha/src/sha.js',];
  return gulp.src(targets)
  .pipe(concat('third_libs.js'))
//  .pipe(uglify({ mangle: false }))
  .pipe(gulp.dest('staticFiles'));

});



var onError = function(err){
  gutil.beep();
  console.log(err);
  this.emit('end');
};

gulp.task('buildStyleSheet', function() {
  return gulp.src('clientCode/styles/main.less')
    .pipe(plumber({errorHandler: onError}))
    .pipe(less())
    .pipe(autoprefixer())
    //.pipe(cssmin())
    .pipe(gulp.dest('staticFiles'));
});
gulp.task('wacthStyleSheet',['buildStyleSheet'],function(){
  gulp.watch('clientCode/styles/**/*.less', ['buildStyleSheet']);
});
gulp.task('watch',['wacthStyleSheet','watchServer','watchClient']);
gulp.task('build',['buildStyleSheet','buildThird','buildActions','buildClient','buildServer']);
